package com.h3bpm.web.common.controller;

import OThinker.Common.DotNetToJavaStringHelper;
import OThinker.Common.Organization.Models.User;
import OThinker.H3.Controller.ControllerBase;
import OThinker.H3.Controller.RestfulApi.Entity.InstanceView;
import OThinker.H3.Controller.RestfulApi.Entity.RestfulApiResult;
import OThinker.H3.Entity.Instance.InstanceContext;
import OThinker.H3.Entity.Instance.InstanceState;
import OThinker.H3.Entity.Messages.Instance.CancelInstanceMessage;
import OThinker.H3.Entity.Messages.MessageEmergencyType;
import OThinker.H3.Entity.Tracking.UserLog;
import OThinker.H3.Entity.Tracking.UserLogType;
import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.h3bpm.base.util.SheetUtility;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.security.sasl.AuthenticationException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;

/**
 * 第三方系统取消流程
 * @author ：cjj
 * @date ：Created in 2020/8/25 20:05
 */
@RestController
@RequestMapping("/Portal/Instance")
public class CancelInstanceController extends ControllerBase {

    ObjectMapper mapper = new ObjectMapper();

    JavaType javaType = mapper.getTypeFactory().constructParametricType(Map.class, String.class, Object.class);

    private static final long serialVersionUID = 8557622593209924253L;

    private final static Logger logger = LoggerFactory.getLogger(CancelInstanceController.class);

    @Override
    public String getFunctionCode() {
        return null;
    }

    @Autowired
    public HttpServletRequest request;

    public HttpServletResponse response;

    public Authentication authentication;


    protected boolean setAuthenticationValue(String systemCode, String secret)
            throws Exception {
        authentication = new Authentication(systemCode, secret);
        return validateSoapHeader();
    }

    private boolean validateSoapHeader() throws Exception {
        if (authentication == null) {
            logger.info("请输入系统认证信息....");
            return false;
        }
        boolean result = false;
        try {
            String systemCode = authentication.getSystemCode();
            String secret = authentication.getSecret();
            logger.info("开始系统认证 -> systemCode: " + systemCode + ", secret: "
                    + secret);
            result = getEngine().getSSOManager().ValidateSSOSystem(systemCode,
                    secret);
            if (!result) {
                logger.info("系统认证信息不正确....");
                return false;
            }
        } catch (Exception e) {
            logger.info("系统认证失败...." + e.getMessage());
            return false;
        }
        return result;
    }

    public class Authentication {

        public Authentication() {
        }

        public Authentication(String systemCode, String secret)
                throws AuthenticationException {
            this.systemCode = systemCode;
            this.secret = secret;
        }

        private String systemCode;
        private String secret;

        public String getSystemCode() {
            return systemCode;
        }

        public void setSysteemCode(String systemCode) {
            this.systemCode = systemCode;
        }

        public String getSecret() {
            return secret;
        }

        public void setSecret(String secret) {
            this.secret = secret;
        }

    }

    /**
     * 取消流程实例(可批量处理，参数instanceId传值多个用分号;隔开)
     *
     * @param instance
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "/CancelInstance",method={RequestMethod.GET,RequestMethod.POST})
    @ResponseBody
    public final Object CancelInstance(@RequestBody InstanceView instance){
        logger.info("取消流程实例,instanceId:"+instance.getInstanceId()+"-----systemCode:"+instance.getSystemCode()+"--------secret:"+instance.getSecret());
        try {
            if (!setAuthenticationValue(instance.getSystemCode(), instance.getSecret())) {
                return new RestfulApiResult(500,"系统认证失败，请添加正确的系统编码或系统秘钥", Boolean.FALSE);
            }
            if (DotNetToJavaStringHelper.isNullOrEmpty(instance.getInstanceId())) {
                return new RestfulApiResult(500,"流程instanceId为空或为null", Boolean.FALSE);
            }
            String[] instanceIds = instance.getInstanceId().split(";");
            for (int i = 0; i < instanceIds.length; i++) {
                // 取消该流程
                InstanceContext InstanceContext = this.getEngine().getInstanceManager().GetInstanceContext(instanceIds[i]);
                if (InstanceContext != null&&!InstanceContext.getState().equals(InstanceState.Finished)) {
                    CancelInstanceMessage cancelMessage = new CancelInstanceMessage(MessageEmergencyType.Normal, instanceIds[i], true);
                    this.getEngine().getInstanceManager().SendMessage(cancelMessage);
                    // 记录日志
                    UserLog log = new UserLog(UserLogType.CancelInstance, User.AdministratorID, InstanceContext.getBizObjectSchemaCode(),
                            InstanceContext.getBizObjectId(), instanceIds[i], instanceIds[i], null, null, SheetUtility.GetClientIP(request), SheetUtility.GetClientPlatform(request), SheetUtility.GetClientBrowser(request));
                    this.getEngine().getUserLogWriter().Write(log);
                }
            }
        }catch (Exception e){
            logger.error("取消流程实例请求失败，详细情况："+e);
            e.printStackTrace();
        }
        return new RestfulApiResult(200, "success", Boolean.TRUE);
    }
}
